//
//  KUserCenterViewController.m
//  Keping
//
//  Created by 柯平 on 2017/6/30.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KUserCenterViewController.h"
#import "KUserData.h"
#import "KUserProfileHeaderView.h"
#import "KChangePwdViewController.h"
#import "KInputViewController.h"
#import "KUploadAvatarRequest.h"
#import "KUploadImageRequest.h"
#import "KUpdateProfileRequest.h"
#import "AppDelegate.h"
#import "KUserCenterQRView.h"
#import <XXNibBridge/XXNibBridge.h>
#import "KUserAuthenticationVC.h"

@interface KUserCenterViewController ()<KGetImageDelegate>
@property(nonatomic,strong)NSArray* items;
@property(nonatomic,strong)KUserProfileHeaderView* headView;
@property(nonatomic, strong)KUserCenterQRView *qrView;

@end

@implementation KUserCenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    @weakify(self);
    
    self.items = @[@[@"IC Info"],
  @[@"Phone:"],@[@"Email:"],@[@"Home Address:"],@[@"Password"]];
    _headView = [[KUserProfileHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth/2)];
    _headView.editBlock = ^(BOOL isName) {
        if (isName) {
            [weak_self editName];
        }else{
            weak_self.imageDelegate = weak_self;
            [weak_self editAvatar];
        }
    };
    _headView.user = [KPartyView unarchive];
    self.tableView.refreshEnable = NO;
    self.tableView.loadmoreEnable = NO;
    self.tableView.tableHeaderView = _headView;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshUserInfo) name:KUpdateUserInfoSuccessNotification object:nil];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"profile_enum"] style:UIBarButtonItemStyleDone target:self action:@selector(actionForQR)];
}

- (KUserCenterQRView *)qrView {
    if (!_qrView) {
        _qrView = [KUserCenterQRView xx_instantiateFromNib];
        _qrView.frame = self.view.bounds;
        _qrView.userInteractionEnabled = YES;
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddeQRView)];
        [_qrView addGestureRecognizer:gesture];
    }
    return _qrView;
}

- (void)actionForQR {
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [app.window addSubview:self.qrView];
}

- (void)hiddeQRView {
    [self.qrView removeFromSuperview];
}

-(void)refreshUserInfo{
    self.headView.user = [KPartyView unarchive];
    [self.tableView reloadData];
}

-(void)editName{
    KInputViewController* vc = [[KInputViewController alloc] initWithTitle:@"Change Username" placeholder:@"Please enter a nickname" key:@"nickName" operate:KInputOperateTypeUpdateName];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)editAvatar{
    UIAlertController* sheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [sheet addAction:[UIAlertAction actionWithTitle:@"Camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self getImageWithType:UIImagePickerControllerSourceTypeCamera];
    }]];
    [sheet addAction:[UIAlertAction actionWithTitle:@"Album" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self getImageWithType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
    }]];
    [sheet addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:sheet animated:YES completion:nil];
}

-(void)didGetImage:(UIImage *)image
{
    if (!image) {
        [self showErrorText:@"Get image failed!"];
        return;
    }else{
        KUploadImageRequest* imgRequest = [[KUploadImageRequest alloc] initWithUploadImage:image compression:0.5];
        [imgRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
            KRequestImgData* data = [KRequestImgData modelWithJSON:request.responseData];
            if (data.statusCode == 200) {
                if (![data.imageUrl isNotBlank]) {
                    [self showErrorText:@"上传图片失败"];
                    return;
                }
                KLog(@"img:%@",data.imageUrl);
                //本地保存
                KPartyView* user = [KPartyView unarchive];
                user.profile = [NSString stringWithFormat:@"%@%@",KGetImageURL,data.imageUrl];
                if ([user archive]) {
                    KLog(@"用户信息保存成功！");
                    self.headView.user = user;
                }
                
                //服务器保存
                KUpdateProfileRequest* updateRequest = [[KUpdateProfileRequest alloc] init];
                updateRequest.params = [NSDictionary dictionaryWithObjectsAndKeys:data.imageUrl?:@"",@"profile", nil];
                [updateRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
                    KRequestData* data = [KRequestData modelWithJSON:request.responseData];
                    if (data.statusCode == 200) {
                        [self showSuccess:@"Upload avatar success!"];
                    }else{
                        [self showErrorText:data.msg errCode:data.statusCode];
                    }
                } failure:^(__kindof KBaseRequest * _Nonnull request) {
                    //
                }];
                
            }else{
                [self showErrorText:data.msg errCode:data.statusCode];
            }
        } failure:^(__kindof KBaseRequest * _Nonnull request) {
            KLog(@"error");
        }];
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.items.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [(NSArray*)self.items[section] count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString* title = self.items[indexPath.section][indexPath.row];
    KPartyView* user = [KPartyView unarchive];
    KTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:[KTableViewCell className]];
    if (!cell) {
        cell = [[KTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:[KTableViewCell className]];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.textLabel.text = title;
    cell.detailTextLabel.text = @"";
    if ([@"IC Info" isEqualToString:title]) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }else if ([@"Phone:" isEqualToString:title]){
        cell.detailTextLabel.text = user.phone;
    }else if ([@"Email:" isEqualToString:title]){
        cell.detailTextLabel.text = user.email;
    }else if ([@"Home Address:" isEqualToString:title]){
        cell.detailTextLabel.text = user.addr;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }else if ([@"Password" isEqualToString:title]){
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
    }

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString* title = self.items[indexPath.section][indexPath.row];
    if ([@"IC Info" isEqualToString:title]) {
        KUserAuthenticationVC *autthen = [[KUserAuthenticationVC alloc] init];
        [self.navigationController pushViewController:autthen animated:YES];
    }else if ([@"Phone:" isEqualToString:title]){
        
    }else if ([@"Email:" isEqualToString:title]){
        
    }else if ([@"Home Address:" isEqualToString:title]){
        KInputViewController* vc = [[KInputViewController alloc] initWithTitle:@"Enter the address" placeholder:@"Enter the address" key:@"addr" operate:KInputOperateTypeUpdateAddr];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([@"Password" isEqualToString:title]){
        KChangePwdViewController* vc = [KChangePwdViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
